package bigoo.ds.message;

import java.util.Collection;
import java.util.LinkedList;

import bigoo.common.PeerEntry;
import bigoo.common.PeerInfo;
import bigoo.common.communication.AbstractMessage;
import bigoo.common.communication.InvalidMessageException;
import bigoo.common.communication.Message;
import bigoo.common.communication.MessageBuilder;

public class GetPeersAnswerMessage extends AbstractMessage {

    public static final String MSG_IDENTIFIER = "GET_PEERS_ANSWER";

    private Collection<PeerInfo> peers = new LinkedList<PeerInfo>();

    public GetPeersAnswerMessage(String peerID) {
	super(peerID, MSG_IDENTIFIER);
    }

    public GetPeersAnswerMessage(String peerID, Collection<PeerEntry> entries) {
	this(peerID);
	for (PeerEntry entry : entries) {
	    this.addPeer(entry.getPeerID(), entry.getAddress(), entry.getPort());
	}
    }

    @Override
    public String getRawMessage() {
	StringBuilder buf = new StringBuilder();
	buf.append(this.getSenderID() + SEPARATOR + MSG_IDENTIFIER + SEPARATOR);
	for (PeerInfo peer : this.peers) {
	    buf.append(peer.toString());
	    buf.append(LIST_SEPARATOR);
	}
	buf.append(END_OF_MESSAGE);
	return buf.toString();
    }

    public Collection<PeerInfo> getPeers() {
	return this.peers;
    }

    public void addPeer(String peerID, String address, int port) {
	this.peers.add(new PeerInfo(peerID, address, port));
    }

    public static class Builder implements MessageBuilder {
	@Override
	public Message parseMessage(String rawMessage) throws InvalidMessageException {
	    try {
		String senderID = parseSenderID(rawMessage);
		GetPeersAnswerMessage msg = new GetPeersAnswerMessage(senderID);
		String[] params = parseListParams(rawMessage);
		for (String param : params) {
		    String[] fields = parseParams(param);
		    msg.addPeer(fields[0], fields[1], Integer.parseInt(fields[2]));
		}
		return msg;
	    } catch (ArrayIndexOutOfBoundsException e) {
		throw new InvalidMessageException();
	    }
	}

    }
}
